package com.woniuxy.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JWTUtil {
    //过期时间 未来会频繁变化修改，所以提出来 目前过期时间5min
    private static final long EXPIRE_TIME=50*60*1000;

    /**
     * 签名生成JWT
     * @param username
     * @param password
     * @return
     */
    public static String sign(String username ,String password){
        Algorithm algorithm = Algorithm.HMAC256(password);
        return JWT.create().withClaim("username",username)
                .withExpiresAt(new Date(System.currentTimeMillis()+EXPIRE_TIME))
                .sign(algorithm);
    }

    /**
     * 使用token 用户和密码 进行内部直接jwt校验
     * @param token
     * @param username
     * @param password
     * @return
     */
    public static boolean verify(String token,String username,String password){
        Algorithm algorithm = Algorithm.HMAC256(password);
        JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username)
                .build();
        verifier.verify(token);
        return true;
    }

    /**
     * 根据token获取username用户名
     * @param token
     * @return
     */
    public static String getUsername(String token){
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim("username").asString();
    }
}
